package com.extweb4j.core.daoaload;

import java.util.ArrayList;
import java.util.List;

import com.extweb4j.core.model.ExtMenu;
import com.extweb4j.core.model.ExtRoleMenu;
import com.extweb4j.core.model.ExtUserRole;
import com.jfinal.plugin.ehcache.IDataLoader;
/**
 * 更新keys获取数据组和数据项
 * 
 */
public class MenuAuthDataLoader  implements IDataLoader{
	
	private String uid;
	
	@Override
	public Object load() {
		List<ExtMenu> menus  = new ArrayList<ExtMenu>();
		
		/**
		 * 获取角色ID列表
		 */
		List<ExtUserRole> userRoles = ExtUserRole.dao.findByAttr("user_id",getUid());
		List<String> rids = new ArrayList<String>();
		for(ExtUserRole eur : userRoles){
			rids.add(eur.getStr("role_id"));
		}
		/**
		 * 获取菜单ID列表
		 */
		List<ExtRoleMenu> roleMenus = ExtRoleMenu.dao.findMenusByIn(rids);
		if(roleMenus == null || roleMenus.size()==0){
			return menus;
		}
		List<String> meids = new ArrayList<String>();
		
		for(ExtRoleMenu rm : roleMenus){
			String mid = rm.getStr("menu_id");
			if(!meids.contains(mid)){
				meids.add(mid);
			}
		}
		
		/**
		 * 查询菜单
		 */
		menus =  ExtMenu.dao.findByPidAndIds("0",meids.toArray());
		for(int i=0;i<menus.size();i++){
			ExtMenu menu = menus.get(i);
			menu.set("leaf","0");
			List<ExtMenu> menus2 =  ExtMenu.dao.findByPidAndIds(menu.getStr("id"),meids.toArray());
			for(ExtMenu menu2 : menus2){
				menu2.set("leaf","1");
			}
			menu.put("children",menus2);
		}
		
		return menus;
	}

	public String getUid() {
		return uid;
	}

	public void setUid(String uid) {
		this.uid = uid;
	}

	public MenuAuthDataLoader() {
		super();
	}

	public MenuAuthDataLoader(String uid) {
		super();
		this.uid = uid;
	}
	
	
}
